package org.jeecg.common.handler;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * list转换string
 *
 * @author chechen
 * @since 2021-12-18
 */
public class ListToStringHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex, List<String> parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(columnIndex, StringUtils.collectionToDelimitedString(parameter, StringPool.COMMA));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String value = resultSet.getString(columnName);
        return Arrays.asList(StringUtils.tokenizeToStringArray(value, StringPool.COMMA));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String value = resultSet.getString(columnIndex);
        return Arrays.asList(StringUtils.tokenizeToStringArray(value, StringPool.COMMA));
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String value = callableStatement.getString(columnIndex);
        return Arrays.asList(StringUtils.tokenizeToStringArray(value, StringPool.COMMA));
    }

}
